package cn.cat.ip138;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.util.NodeList;


import java.io.IOException;

public class Ip138 {

    public static String ip2addr(String ip) throws Exception {

        DefaultHttpClient httpclient = new DefaultHttpClient();
        String html = "";

        try {
            HttpGet httpget = null;
            //创建HttpGet对象
            httpget = new HttpGet("http://www.ip138.com/iplookup.asp?ip=" + ip + "&action=2");
            //使用execute方法发送HTTPGET请求，并返回HttpResponse对象
            HttpResponse response = httpclient.execute(httpget);
            //使用getEntity方法获得返回结果
            HttpEntity entity = response.getEntity();
            //读取response响应内容
            html = EntityUtils.toString(entity,"utf-8");
            //关闭底层流
            EntityUtils.consume(entity);
        } catch (IOException e) {
            throw e;
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
        /**
         * 利用Parser解析HTML，将标签
         下的内容存储到nodeList里，并获取第一个
         下的内容，用split分割后获取最终的结果是 日本
         */
        Parser myParser =Parser.createParser(html, "utf-8");
        NodeFilter filter =new TagNameFilter("li");

        NodeList nodeList =myParser.parse(filter);
        System.out.println(nodeList);
        String result = nodeList.elementAt(0).toPlainTextString();
        System.out.println(result);
        String address = result.split("：")[1];


        return address;

    }

    public static void main(String[] args) throws Exception{

            ip2addr("36.19.167.0");

    }
}
